<?php

namespace App\Http\Middleware;

use Closure;

class ApiCache
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if($request->isMethod('GET')){
            $uri = $request->getUri();
            $params = $request->all();
            $keyStr = $uri.'::';
            foreach($params as $key => $val){
                $keyStr = $keyStr.$key.':'.$val.'::';
            }
            $key = md5($keyStr);
            $data = \Cache::get($key);
            if($data){
                $data = json_decode($data,true);
                $response = response()->json($data);
                $response->isCached = true;//添加这个属性是为了避免监听器重复写入缓存
                return $response;
            }

        }
        return $next($request);
    }

}
